package com.gjy.concurrency.lock;

import org.junit.jupiter.api.Test;

import java.util.concurrent.locks.LockSupport;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-03-31 09:42:52
 */
public class Lock3Test {

    Thread t1, t2, t3;

    @Test
    public void test2() {
        t1 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName());
            LockSupport.unpark(t2);
            LockSupport.park();
        }, "A");
        t2 = new Thread(() -> {
            LockSupport.park();
            System.out.println(Thread.currentThread().getName());
            LockSupport.unpark(t3);
        }, "B");
        t3 = new Thread(() -> {
            LockSupport.park();
            System.out.println(Thread.currentThread().getName());
            LockSupport.unpark(t1);
        }, "C");
        t2.start();
        t1.start();
        t3.start();
    }

    private static final Object lock = new Object();
    private int flag = 1;

    @Test
    public void test1() {

        new Thread(() -> {
            synchronized (lock) {
                while (flag != 2) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                flag++;
                System.out.println(Thread.currentThread().getName());
                lock.notifyAll();
            }
        }, "B").start();

        new Thread(() -> {
            synchronized (lock) {
                while (flag != 3) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                flag++;
                System.out.println(Thread.currentThread().getName());
                lock.notifyAll();
            }
        }, "C").start();

        new Thread(() -> {
            synchronized (lock) {
                while (flag != 1) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                flag++;
                System.out.println(Thread.currentThread().getName());
                lock.notifyAll();
            }
        }, "A").start();

    }
}
